﻿using System;
using System.Drawing;
using pub.CmdUI.Cmd;
using pub.CmdUI.UI.Control;
using pub.NET20Fix;

namespace todo.Ribbon.CmdUI
{
    public class RibbonToggleButtonGroupUI : IItemsControlUI
    {
        private RibbonControl _groupControl;
        private RibbonToggleButton[] _buttons;
        private Action _triggerCallback;
        private int? _selectedIndex;
        private int? _clickedIndex;

        public RibbonToggleButtonGroupUI(RibbonControl groupControl, RibbonToggleButton[] buttons)
        {
            this._groupControl = groupControl;
            this._buttons = buttons;

            for (var n = 0; n < buttons.Length; n++)
            {
                var index = n;
                buttons[n].OnClick += (sender, args) => {
                    buttons[index].Checked = false;
                    _clickedIndex = index;
                    if (_triggerCallback != null)
                    {
                        _triggerCallback();
                    }
                };
            }
        }

        public Action TriggerCallback
        {
            set { _triggerCallback = value; }
        }

        public Bitmap Icon
        {
            set { throw new NotImplementedException(); }
        }

        public string Label
        {
            set { throw new NotImplementedException(); }
        }

        public string Tooltip
        {
            set { throw new NotImplementedException(); }
        }

        public void Update(ICmd cmd)
        {
            _groupControl.Enabled = cmd.State.Enabled;

            SetSelectedButton((cmd.State as IItemsCmdState).SelectedIndex);
        }

        private void SetSelectedButton(int? selectedIndex)
        {
            if (selectedIndex == _selectedIndex)
            {
                return;
            }
            if (_selectedIndex.HasValue)
            {
                _buttons[_selectedIndex.Value].Checked = false;
            }
            _selectedIndex = selectedIndex;
            if (_selectedIndex.HasValue)
            {
                _buttons[_selectedIndex.Value].Checked = true;
            }
        }

        int? IItemsControlUI.SelectedItemIndex
        {
            get { return _clickedIndex; }
        }
    }
}